<?php
/**
 * EGGMS 画材全免计划文件
 * @authors 杨浩 (solaao@163.com)
 * @date    2014-09-18 09:53:31
 * @version $Id$
 */

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');

/*上传录取图片*/
if ($_REQUEST['act'] == 'upload_pic') {
//初始返回数据
    $return['error']="0";
    $return['content']="";
    //允许上传类型
    $uptypes=array(
        'image/jpg',
        'image/jpeg',
        'image/png',
        'image/pjpeg',
        'image/gif',
        'image/bmp',
        'image/x-png'
        );
    $max_file_size = 2000000;     //上传文件大小限制, 单位BYTE
    $url           = "recruit_pic/"; //上传文件路径
    $file          = $_FILES["file"]; //获取文件
    $filename      = $file["tmp_name"];
    if(!in_array($file["type"], $uptypes))
    //检查文件类型
    {
        $return['error']="1";
        $return['content']="图片格式不正确!";
        die(json_encode($return));
    }
    //检查上传目录是否存在
    if(!file_exists($url))
    {
        //创建目录
        mkdir($url);
    }

    $filename=$file["tmp_name"];
    $image_size = getimagesize($filename);
    $pinfo=pathinfo($file["name"]);
    $ftype=$pinfo['extension'];
    $img_name=$_REQUEST['user_id']."_".time().".".$ftype;
    $destination = ROOT_PATH . $url.$img_name; //上传图片地址
    $destination2 = $url.$img_name; //上传图片地址


    if(!move_uploaded_file($filename,$destination) || !FTP()->upload($destination, $destination2))//判断是否移动成功
    {
        $return['error']="1";
        $return['content']="移动失败";
        die(json_encode($return));
    }
    sleep(1);
    $return['error']="2";
    $return['content']="移动成功";
    $return['pic']=$destination2;
    die(json_encode($return));
}

if ($_REQUEST['act'] == 'update_three') {
    if(!$_SESSION['user_id']){
        $result = array( 'message' => '请登录后再操作','error'=>'601');
        echo $json->encode($result);
        exit;
    }else{
        $user_id = $_SESSION['user_id'];
    }
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $result = array( 'message' => '','error'=>'0');
    $sql = "SELECT realname,exam_year FROM ".$ecs->table('user_freeplan')." WHERE user_id = $user_id ";
    $note = $db->getRow($sql);
    if ($note['exam_year']!='2015年') {
        $result = array( 'message' => '只有报考年份为2015年的用户才可以填写该信息','error'=>'602');
        echo $json->encode($result);
        exit;
    }
    $recruitSchool = !empty($_REQUEST['recruitSchool'])?$_REQUEST['recruitSchool']:'';
    $recruitPic    = !empty($_REQUEST['recruitPic'])?$_REQUEST['recruitPic']:'';

    $sql= " UPDATE ".$ecs->table('user_freeplan').
          " set recruit_school= '$recruitSchool' , notice_pic= '$recruitPic'".
          " WHERE user_id=$user_id";
    $db->query($sql);
    echo $json->encode($result);
    exit;
}





assign_template();
$position = assign_ur_here();

$action = isset($_REQUEST['act']) ? $_REQUEST['act'] : 'default';
$step   = $_REQUEST['step'];


/* 默认画材全免计划主板面 */
if( $action == 'default' ){
    // 获取总奖金和总参与数量
    $sql = "SELECT COUNT(*) AS count,SUM(money) AS sum FROM " . $ecs->table('user_freeplan');
    $stats = $db->getRow($sql);
    $stats = $stats?$stats:'0';
    $stats['sum'] = $stats['sum']+1500000;
    $stats['count'] += substr(time(),2,4) - 2930;
    $stats['count'] +=3000;
    //$stats['sum'] = num_format($stats['sum']);

    // 获取10个已报名的名字
    $sql = "SELECT realname FROM " . $ecs->table('user_freeplan') . " LIMIT 5,10";
    $user_list = $db->getAll($sql);
    foreach ($user_list as $key => $value) {
        $user_list[$key]['key'] = $key+1;
        // 判断姓名字数从而截取不同位数
        if(strlen($user_list[$key]['realname']) > 9){
            $user_list[$key]['realname'] = '**'.mb_substr($value['realname'], 2,2, 'utf-8');
        }else{
            $user_list[$key]['realname'] = '*'.mb_substr($value['realname'], 1,2, 'utf-8');
        }
    }

    // 获取奖金排行榜前5名
    $sql = "SELECT uf.* FROM " . $ecs->table('user_freeplan') . " uf ORDER BY uf.money DESC LIMIT 0,8";
    $rank_list = $db->getAll($sql);
    require(dirname(__FILE__) . './../data/false_data_1.php');
    /*组建虚假数据*/
    for ($i=0; $i < 8 ; $i++) {
        $user_false[$i]['realname'] =$name[$i];
        $user_false[$i]['idcardnumber'] =$idCard[$i];
        $user_false[$i]['academy'] =$school[$i];
        $user_false[$i]['money'] =$money[$i];
    }
    /*合并数据*/
    $rank_list = array_merge($rank_list,$user_false);
    $rank_list = bubbleSort2($rank_list,'money');
    array_splice($rank_list, 8);

    /*821发放奖金数据*/
    require(dirname(__FILE__) . './../data/false_data_2.php');
    $falseNum = count($name2);
    /*组建虚假数据*/
    for ($i=0; $i < $falseNum ; $i++) {
        $user_false2[$i]['address'] =$address2[$i];
        $user_false2[$i]['realname'] =$name2[$i];
        $user_false2[$i]['idcardnumber'] =$idCard2[$i];
        $user_false2[$i]['academy'] =$school2[$i];
        $user_false2[$i]['money'] =$money2[$i];
    }
    $user_false2 = bubbleSort2($user_false2,"money");
    $user_false2 = array_values($user_false2);


    
    foreach ($user_false2 as $key => $value) {
        $user_false2[$key]['key'] = $key+1;
        //判断姓名字数从而截取不同位数
        if(strlen($user_false2[$key]['realname']) > 9){
            $user_false2[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 2,2, 'utf-8');
        }else{
            $user_false2[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 1,2, 'utf-8');
        }
        $user_false2[$key]['idcardnumber'] = substr($value['idcardnumber'],0,4).'<font style="font-family:宋体">*********</font>'.substr($value['idcardnumber'],-4);
    }
    $smarty->assign('user_false2',      $user_false2);    // 发放奖金数据




    foreach ($rank_list as $key => $value) {
        if($value['money']>=0){
            $rank_list[$key]['key'] = $key+1;
            // 判断姓名字数从而截取不同位数
            if(strlen($rank_list[$key]['realname']) > 9){
                $rank_list[$key]['realname'] = '**'.mb_substr($value['realname'], 2,2, 'utf-8');
            }else{
                $rank_list[$key]['realname'] = '*'.mb_substr($value['realname'], 1,2, 'utf-8');
            }

            $rank_list[$key]['idcardnumber'] = substr($value['idcardnumber'],0,4).'**********'.substr($value['idcardnumber'],-4);
        }else{
            unset($rank_list[$key]);
        }
    }


    // 获取当前用户报名信息
    if($_SESSION['user_id']){

        $smarty->assign('user_id', $_SESSION['user_id']);

        // 查询用户是否已经报名
        $sql = "SELECT COUNT(*) FROM " . $ecs->table('user_freeplan') . " WHERE user_id = $_SESSION[user_id]";
        if($db->getOne($sql)){  // 已报名
            //header('location:user.php');
            $smarty->assign('sign',1);
        }else{
            $smarty->assign('sign',0);
        }

        // 查询用户奖金以及排名
        $sql = "SELECT count(*) as rank, b.money FROM " . $ecs->table('user_freeplan') . "AS a LEFT JOIN " .
                $ecs->table('user_freeplan') . "AS b " .
                " ON a.money > b.money " . " WHERE b.user_id = ". $_SESSION[user_id];
        $user_freeplan = $db->getRow($sql);
    }

    $smarty->assign('user_freeplan', $user_freeplan); // 获取当前用户报名信息
    $smarty->assign('stats', $stats);               // 奖金总额和总参与人数
    $smarty->assign('user_list', $user_list);       // 10个已报名的名字
    $smarty->assign('rank_list', $rank_list);       // 奖金排行榜前5名
    $smarty->assign('top_title', '圆梦美院计划');
    $smarty->assign('page_title',      $position['title']);    // 页面标题





    /*划分录入时间段*/
    $time_num = 1;
    $time = time();

    //     /*测试*/
    // $time =1436889601;
    $where = '1 ';
    $sort = "ORDER BY uf.link_mark DESC, uf.only_mark ASC";
    if ($time<1435593600) {

        $time_num =1;
        $where = $where . "AND link_mark > 0 AND only_mark >0 ";
        if ($_SESSION['user_id']) {
            /*查询用户能否填写信息*/
            $sql =  " SELECT count(*) FROM ".$ecs->table('user_freeplan').
                    " WHERE user_id = ".$_SESSION['user_id']." AND (link_mark = 0 OR only_mark = 0)";
            $is_input = $db->getOne($sql);
            $is_input = !empty($is_input)?1:0;
            $smarty->assign('is_input', $is_input);
        }else{
            $smarty->assign('is_input', 1);
        }
    }
    elseif ($time>1435593600&&$time<1436889600) {
        $time_num =2;
        $where = $where . "AND link_mark > 0 AND only_mark >0 AND height_mark > 0 ";
        if ($_SESSION['user_id']) {
            /*查询用户能否填写信息*/
            $sql =  " SELECT count(*) FROM ".$ecs->table('user_freeplan').
                    " WHERE user_id = ".$_SESSION['user_id']." AND (link_mark = 0 OR only_mark = 0 OR height_mark = 0)";
            $is_input = $db->getOne($sql);
            $is_input = !empty($is_input)?1:0;
            $smarty->assign('is_input', $is_input);
        }else{
            $smarty->assign('is_input', 1);
        }
    }
    elseif ($time>1436889600&&$time<1439136000) {
        $time_num =3;
        $where = $where . "AND recruit_school !='' ";
        if ($_SESSION['user_id']) {
            /*查询用户能否填写信息*/
            $sql =  " SELECT count(*) FROM ".$ecs->table('user_freeplan').
                    " WHERE user_id = ".$_SESSION['user_id']." AND recruit_school ='' ";
            $is_input = $db->getOne($sql);
            $is_input = !empty($is_input)?1:0;
            $smarty->assign('is_input', $is_input);
        }else{
            $smarty->assign('is_input', 1);
        }
    }
    elseif ($time>1439136000) {
        $time_num =4;
    }



    /*获取已填写的用户信息*/
    $sql =  " SELECT uf.user_id,uf.money, uf.realname ,uf.link_mark,uf.only_mark,uf.height_mark,uf.recruit_school FROM " . $ecs->table('user_freeplan') . " uf"." WHERE $where $sort LIMIT 0,10";
    $mark_list = $db->getAll($sql);
        /*虚假数据*/
    require(ROOT_PATH . './data/false_data.php');
    if (count($mark_list)<10) {
       $last_data = array_merge($mark_list,$false_data);
    }else{
        $last_data = $mark_list;
    }
    if (count($last_data)>10) {
        array_splice($last_data, 10);
    }
    $post_data =array_values($last_data);
    $post_data = bubbleSort2($post_data);
    foreach ($post_data as $key => $value) {
            $post_data[$key]['num'] = $key +1;
        if(strlen($post_data[$key]['realname']) > 9){
            $post_data[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 2,2, 'utf-8');
        }else{
            $post_data[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 1,2, 'utf-8');
        }

        if (!empty($_SESSION['user_id']) && $value['user_id'] == $_SESSION['user_id']) {
            $user_num = $key+1;
        }

    }
    if (!empty($user_num)) {
        $smarty->assign('user_num', $user_num);
    }
    // 获取用户当前信息
    if($_SESSION['user_id']){
        $sql = "SELECT uf.* FROM " . $ecs->table('user_freeplan') . " uf WHERE uf.user_id = $_SESSION[user_id]";
        $user_freeplan = $db->getRow($sql);

        if($user_freeplan){
            $sql = "SELECT COUNT(*) FROM " . $ecs->table('user_freeplan') . " uf WHERE uf.money > $user_freeplan[money] OR (uf.money = $user_freeplan[money] AND uf.addtime <= $user_freeplan[addtime])";
            $user_freeplan['key'] = $db->getOne($sql);
            // 判断姓名字数从而截取不同位数
            if(strlen($user_freeplan['realname']) > 9){
                $user_freeplan['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($user_freeplan['realname'], 2,2, 'utf-8');
            }else{
                $user_freeplan['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($user_freeplan['realname'], 1,2, 'utf-8');
            }
            $user_freeplan['idcardnumber'] = substr($user_freeplan['idcardnumber'],0,4).'<font style="font-family:宋体">*********</font>'.substr($user_freeplan['idcardnumber'],-4);
            $smarty->assign('user_freeplan', $user_freeplan);
        }
    }
    $smarty->assign('post_data', $post_data);
    $smarty->assign('time_num', $time_num);
    $smarty->assign('action', $action);

    $smarty->display('freeplan/freeplan.dwt');
}

/* 奖金排行榜 */
elseif( $action == 'sign_rank' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    $sql = "SELECT uf.* FROM " . $ecs->table('user_freeplan') . " uf ORDER BY uf.money DESC LIMIT 0,100";
    $rank_list = $db->getAll($sql);
    require(dirname(__FILE__) . './../data/false_data_1.php');
    /*组建虚假数据*/
    for ($i=0; $i < 99 ; $i++) {
        $user_false[$i]['realname'] =$name[$i];
        $user_false[$i]['idcardnumber'] =$idCard[$i];
        $user_false[$i]['academy'] =$school[$i];
        $user_false[$i]['money'] =$money[$i];
    }
    /*合并数据*/
    $rank_list = array_merge($rank_list,$user_false);
    $rank_list = bubbleSort2($rank_list,'money');
    array_splice($rank_list, 100);
    foreach ($rank_list as $key => $value) {
        if($value['money']>=0){
            $rank_list[$key]['key'] = $key+1;
            //判断姓名字数从而截取不同位数
            if(strlen($rank_list[$key]['realname']) > 9){
                $rank_list[$key]['realname'] = '***'.mb_substr($value['realname'], 2,2, 'utf-8');
            }else{
                $rank_list[$key]['realname'] = '***'.mb_substr($value['realname'], 1,2, 'utf-8');
            }

            $rank_list[$key]['idcardnumber'] = substr($value['idcardnumber'],0,4).'**********'.substr($value['idcardnumber'],-4);
        }else{
            unset($rank_list[$key]);
        }
    }

    $sign = isset($_REQUEST['sign']) ? $_REQUEST['sign'] : '';

    $back_url = 'freeplan.php';

    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('back_url', $back_url);
    $smarty->assign('top_title', '奖金排行榜');
    $smarty->assign('user_id', $_SESSION['user_id']);
    //$smarty->assign('user_freeplan', $_REQUEST['user_freeplan']);
    $smarty->assign('sign', $sign);
    $smarty->assign('rank_list', $rank_list);
    $smarty->assign('action', $action);
    $smarty->assign('num', $_REQUEST['num']);
    $smarty->display('freeplan/freeplan.dwt');
}

/* 报名开始协议 */
elseif( $action == 'agreement' ){

    if( !$_SESSION['user_id'] ){
        header('location:user.php');
    }

    if( $_REQUEST['sign'] ){        // 已登录，未报名
        $smarty->assign('sign', 1);
    }

    $back_url = 'freeplan.php';

    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('back_url', $back_url);
    $smarty->assign('top_title', '活动规则');
    $smarty->assign('action', $action);
    $smarty->display('freeplan/freeplan.dwt');
}

/* 填写资料 */
elseif( $action == 'write_data' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    $back_url = 'freeplan.php';

    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('back_url', $back_url);
    $smarty->assign('top_title', '填写资料');
    $smarty->assign('action', $action);
    $smarty->display('freeplan/freeplan.dwt');
}
/* 检测身份证是否已注册 */
elseif( $action == 'ajax_check_id' ){

    if(!$_SESSION['user_id']){
        header('location:index.php');
    }

    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $result = array( 'message' => '','error'=>'');
    $sql = "SELECT count(*) FROM " . $ecs->table('user_freeplan') . " WHERE idcardnumber = '" . trim($_POST['data_2']) . "'";
    $result['error'] = $db->getOne($sql);
    echo $json->encode($result);
    exit;
}

/* ajax 先保存已填写的资料 */
elseif( $action == 'save_temp' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    $_SESSION['temp_data'] = $_POST['temp_data'];

    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $result = array( 'message' => '1');
    echo $json->encode($result);
    exit;
}

/* 选择就读学校地区 */
elseif( $action == 'location' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    $type           = isset($_REQUEST['type'])          ? trim($_REQUEST['type'])         : '';
    $parent_id      = isset($_REQUEST['parent_id'])     ? trim($_REQUEST['parent_id'])    : '';
    $region_name    = isset($_REQUEST['region_name'])   ? trim($_REQUEST['region_name'])  : '';

    // 省
    if( $type == 'province' ){
        $top_title = '省份/直辖市';
        $smarty->assign('province_list', get_regions(1, 1));        // 获取省级列表
    }
    // 市
    elseif( $type == 'city' ){
        $top_title = $region_name;
        $smarty->assign('city_list', get_regions(2, $parent_id));        // 获取市级列表
        $_SESSION['temp_data'][8] = $parent_id;       // 把省保存到session中
    }
    // 区
    elseif( $type == 'district' ){
        $top_title = $region_name;
        $smarty->assign('district_list', get_regions(3, $parent_id));        // 获取区级列表
        $_SESSION['temp_data'][9] = $parent_id;       // 把市保存到session中
    }

    $smarty->assign('page_title',   $position['title']);        // 页面标题
    $smarty->assign('top_title', $top_title);
    $smarty->assign('type', $type);
    $smarty->assign('action', $action);
    $smarty->display('freeplan/freeplan.dwt');
}

/*ajax 记录区信息到session*/
elseif( $action == 'save_district' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    $_SESSION['temp_data'][10] = isset($_POST['district']) ? $_POST['district'] : '';

    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $result = array( 'message' => '1');
    echo $json->encode($result);
    exit;
}

/* 处理提交的学校信息 */
elseif ( $action == 'save_school' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    $_SESSION['temp_data'][11] = isset($_POST['data_11']) ? $_POST['data_11'] : '';

    $back_url = 'freeplan.php';

    $smarty->assign('temp_data', $_SESSION['temp_data']);
    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('back_url', $back_url);
    $smarty->assign('top_title', '填写资料');
    $smarty->assign('action', $action);
    $smarty->display('freeplan/freeplan.dwt');
}

/* 报名完成页面 */
elseif ( $action == 'done' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    /* 查询用户是否已经报名 */
    $sql = "SELECT COUNT(*) FROM " . $ecs->table('user_freeplan') . " WHERE user_id = $_SESSION[user_id]";
    if($db->getOne($sql)){// 已报名
        header('location:user.php');
    }
    $error = 0;
    $data['user_id']      = $_SESSION['user_id'];
    $data['realname']     = $_POST['data_1'] ? trim($_POST['data_1']) : $error='realname';
    $data['idcardnumber'] = strlen($_POST['data_2'])==18?trim($_POST['data_2']):$error='idcardnumber';
    $data['mobile']       = strlen($_POST['data_3'])==11?intval($_POST['data_3']):$error='mobile';
    $data['reserve']      = $_POST['data_4'] ? intval($_POST['data_4']) : '';
    $data['email']        = $_POST['data_5'] ? trim($_POST['data_5']) : $error='email';
    $data['schoolname']   = $_POST['data_6'] ? trim($_POST['data_6']) : $error='schoolname';
    $data['schooladdr']   = ($_POST['data_8']&&$_POST['data_9']&&$_POST['data_10']&&$_POST['data_11']) ? (trim($_POST['data_8']).','.trim($_POST['data_9']).','.trim($_POST['data_10']).','.trim($_POST['data_11'])) : $error='schooladdr';
    $data['academy']      = $_POST['data_7'] ? trim($_POST['data_7']) : $error='academy';
    $data['addtime']      = time();
    $data['exam_year']    = $_POST['data_0'] ? trim($_POST['data_0']) : $error='exam_year';

    if( !$erro ){
        $field = array();
        $val   = array();
        foreach ($data as $key => $value) {
            if($value){
                $field[] = "`$key`";
                $val[]   = "'$value'";
            }
        }
        $field = implode(',',$field);
        $val   = implode(',',$val);
        $sql   = "INSERT INTO " . $ecs->table('user_freeplan') . "($field) VALUES($val)";
        if(!$db->query($sql)){
            header('location:freeplan.php?act=agreement&sign=1');
        }
    }else{
        header('location:freeplan.php?act=agreement&sign=1');
    }
    $back_url = 'freeplan.php';
    $smarty->assign('top_title', '圆梦美院计划');
    $smarty->assign('back_url', $back_url);
    $smarty->assign('data', $data);
    // 名师推荐商品
    assign_template();//通用赋值
    $teacher_recommend_id = array(628,521,750,1733,1346,1070,361,1070,369,437);   //名师推荐商品ID
    $teacher_recommend = implode(',', $teacher_recommend_id);             //名师推荐商品ID格式化
    $teacher_recommend_goods = goodsid_get_goods($teacher_recommend);
    $smarty->assign('teacher_recommend_goods', $teacher_recommend_goods);
    $smarty->assign('action', $action);
    $smarty->display('freeplan/freeplan.dwt');
}

/* 视频界面 */
elseif( $action == 'video' ){

    if($_SESSION['user_id']){
        $smarty->assign('user_id', $_SESSION['user_id']);
    }

    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->display('freeplan_video.dwt');
}

/* 全免计划视频评论区域 */
elseif( $action == 'comm_input' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $user_id = !empty($_SESSION['user_id']) ? $_SESSION['user_id'] : '';
    $content = !empty($_REQUEST['content']) ? strip_tags($_REQUEST['content']) : '';
    $time = date("Ymd");
    $return['error'] = 1;
    $return['content'] = "$content";

    // 查询用户是否是一天评论一次
    $sql = "SELECT count(*) FROM ". $ecs->table('freeplan_comment') ."WHERE user_id = $user_id AND add_time = $time";
    $commented = $db->getOne($sql);

    if(!$commented){
        $sql = 'INSERT INTO ' . $ecs->table('freeplan_comment') . ' (user_id, content, add_time) ' .
               "VALUES('$user_id', '$content', '$time')";
        $db->query($sql);
    }

    if( $db->insert_id() ){
        echo $json->encode($return);
        exit();
    }
    $return['error'] = 2;
    $return['content'] = '每天只能评论一次';
    echo $json->encode($return);
    exit();
}

/* 美院英才计划 */
elseif( $action == 'talent_plan' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }

    $back_url = 'freeplan.php';

    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('top_title', '美院英才计划');
    $smarty->assign('back_url', $back_url);
    $smarty->assign('action', $action);
    $smarty->display('freeplan/freeplan.dwt');
}

/* 鸡蛋美术合伙人图片 */
elseif( $action == 'partner' ){

    $pic_id = isset($_REQUEST['pic_id']) ? $_REQUEST['pic_id'] : 1;

    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('pic_id', $pic_id);
    $smarty->display('freeplan_partner.dwt');
}

/*----------------------------------*/

/* 报名填报名表信息 */
elseif($action == 'form'){
    if(!$_SESSION['user_id']){
        header('location:index.php');
    }
    /* 查询用户是否已经报名 */
    $sql = "SELECT COUNT(*) FROM " . $ecs->table('user_freeplan') . " WHERE user_id = $_SESSION[user_id]";
    if($db->getOne($sql)){// 已报名
        header('location:user.php');
    }
    if(empty($_POST['agreement'])) header('location:freeplan.php?act=agreement');
    $smarty->assign('top_title', '画材全免计划');
}

/* 修改报名信息 */
elseif($action == 'edit'){
    if(!$_SESSION['user_id']){
        header('location:index.php');
    }
    /* 查询用户是否已经报名 */
    $sql = "SELECT * FROM " . $ecs->table('user_freeplan') . " WHERE user_id = $_SESSION[user_id]";
    $freeplan = $db->getRow($sql);
    if(!$freeplan){// 未报名
        exit;
    }
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;

    $schooladdr = explode(',',$freeplan['schooladdr']);// 获取就读学校的地址
    $trainaddr = explode(',',$freeplan['trainaddr']);// 获取培训机构的地址
    $smarty->assign('province_list1', get_regions(1, 1));// 获取就读学校的省级列表
    $smarty->assign('city_list1',     get_regions(2, $schooladdr[1]));// 获取就读学校的市级列表
    $smarty->assign('district_list1', get_regions(3, $schooladdr[2]));// 获取就读学校的区级列表
    $smarty->assign('schooladdr', $schooladdr);
    if(count($trainaddr) == 4){ // 如果存在培训机构
        $smarty->assign('province_list2', get_regions(1, 1));// 获取培训机构的省级列表
        $smarty->assign('city_list2',     get_regions(2, $trainaddr[1]));// 获取培训机构的市级列表
        $smarty->assign('district_list2', get_regions(3, $trainaddr[2]));// 获取培训机构的区级列表
        $smarty->assign('trainaddr', $trainaddr);
    }
    $smarty->assign('action', $action);
    $result = array( 'message' => '','error'=>'');
    $result['content'] = $smarty->fetch("library/freeplan.lbi");
    echo $json->encode($result);
    exit;
}

/* 处理修改报名信息 */
elseif($action == 'edit_done'){
    if(!$_SESSION['user_id']){
        header('location:index.php');
    }
    /* 查询用户是否已经报名 */
    $sql = "SELECT COUNT(*) FROM " . $ecs->table('user_freeplan') . " WHERE user_id = $_SESSION[user_id]";
    if(!$db->getOne($sql)){// 已报名
        header('location:user.php');
    }
    $error = 0;
    $data['user_id']      = $_SESSION['user_id'];
    $data['mobile']       = strlen($_POST['data_3'])==11?intval($_POST['data_3']):$error=1;
    $data['reserve']      = $_POST['data_4']?intval($_POST['data_4']):'';
    $data['email']        = $_POST['data_5']?trim($_POST['data_5']):$error=1;
    $data['schoolname']   = $_POST['data_6']?trim($_POST['data_6']):$error=1;
    $data['schooladdr']   = ($_POST['country1']&&$_POST['province1']&&$_POST['city1']&&$_POST['district1'])?(trim($_POST['country1']).','.trim($_POST['province1']).','.trim($_POST['city1']).','.trim($_POST['district1'])):$error=1;
    $data['trainname']    = $_POST['data_7']?trim($_POST['data_7']):'';
    $data['trainaddr']    = ($_POST['country2']&&$_POST['province2']&&$_POST['city2']&&$_POST['district2'])?(trim($_POST['country2']).','.trim($_POST['province2']).','.trim($_POST['city2']).','.trim($_POST['district2'])):'';
    $data['academy']      = $_POST['data_8']?trim($_POST['data_8']):$error=1;
    $data['addtime']      = time();
    if(!$error){
        $updata  = array();
        foreach ($data as $key => $value) {
            if($value){
                $updata[] = "`$key` = '$value'";
            }
        }
        $updata = implode(',',$updata); // 更新的数据
        $sql   = "UPDATE " . $ecs->table('user_freeplan') . " SET $updata WHERE user_id = $_SESSION[user_id]";
        if(!$db->query($sql)){// 更新成功
            header('location:user.php');
        }else{// 更新失败
            header('location:user.php');
        }
    }else{// 提交的数据有错误
        header('location:freeplan.php?act=agreement');
    }
}

/* ajax投票美院 */
elseif($action == 'academy_toupiao'){
    if($_POST['id']){
        $sql = "UPDATE "  . $ecs->table('academy') . " SET count = count + 1 WHERE id = $_POST[id]";
        $db->query($sql);
        $sql = "SELECT count FROM "  . $ecs->table('academy') . " WHERE id = $_POST[id]";
        exit($db->getOne($sql));
    }
}

/* 查看100名排行榜用户 */
elseif($action == 'more'){
    // 获取奖金排行榜前100名
    $sql = "SELECT uf.* FROM " . $ecs->table('user_freeplan') . " uf ORDER BY uf.money DESC LIMIT 0,100";
    $user_list = $db->getAll($sql);
    foreach ($user_list as $key => $value) {
        if($value['money']>=0){
            $user_list[$key]['key'] = $key+1;
            //判断姓名字数从而截取不同位数
            if(strlen($user_list[$key]['realname']) > 9){
                $user_list[$key]['realname'] = '***'.mb_substr($value['realname'], 2,2, 'utf-8');
            }else{
                $user_list[$key]['realname'] = '***'.mb_substr($value['realname'], 1,2, 'utf-8');
            }
        }else{
            unset($user_list[$key]);
        }
    }
    $smarty->assign('user_list', $user_list);
    $smarty->assign('top_title', '画材全免计划排行榜');
}


/*录入资料*/
elseif($action == 'update_one'){
    if(!$_SESSION['user_id']){
        $result = array( 'message' => '请登录后再操作','error'=>'601');
        echo $json->encode($result);
        exit;
    }else{
        $user_id = $_SESSION['user_id'];
    }
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $result = array( 'message' => '','error'=>'0');
    $name     = !empty($_REQUEST['name'])?$_REQUEST['name']:'';
    $sql = "SELECT realname,exam_year FROM ".$ecs->table('user_freeplan')." WHERE user_id = $user_id ";
    $note = $db->getRow($sql);
    if ($name !=$note['realname']) {
        $result = array( 'message' => '名字不正确','error'=>'602');
        echo $json->encode($result);
        exit;
    }
    if ($note['exam_year']!='2015年') {
        $result = array( 'message' => '只有报考年份为2015年的用户才可以填写该信息','error'=>'602');
        echo $json->encode($result);
        exit;
    }
    $linkMark = !empty($_REQUEST['linkMark'])?floatval($_REQUEST['linkMark']):'';
    $onlyMark = !empty($_REQUEST['onlyMark'])?floatval($_REQUEST['onlyMark']):'';

    $sql= " UPDATE ".$ecs->table('user_freeplan').
          " set link_mark= '$linkMark',only_mark= '$onlyMark' ".
          " WHERE user_id=$user_id";
    $db->query($sql);
    echo $json->encode($result);
    exit;
}
/*录入资料*/
elseif($action == 'update_two'){
    if(!$_SESSION['user_id']){
        $result = array( 'message' => '请登录后再操作','error'=>'601');
        echo $json->encode($result);
        exit;
    }else{
        $user_id = $_SESSION['user_id'];
    }
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $result = array( 'message' => '','error'=>'0');
    $sql = "SELECT realname,exam_year FROM ".$ecs->table('user_freeplan')." WHERE user_id = $user_id ";
    $note = $db->getRow($sql);
    if ($note['exam_year']!='2015年') {
        $result = array( 'message' => '只有报考年份为2015年的用户才可以填写该信息','error'=>'602');
        echo $json->encode($result);
        exit;
    }
    $heightMark = !empty($_REQUEST['heightMark'])?floatval($_REQUEST['heightMark']):'';
    $sql= " UPDATE ".$ecs->table('user_freeplan').
          " set height_mark= '$heightMark' ".
          " WHERE user_id=$user_id";
    $db->query($sql);
    echo $json->encode($result);
    exit;
}
/*分数排行榜*/
elseif($action == 'mark_sort'){
/*划分录入时间段*/
    $time_num = 1;
    $time = time();

    $where = '1 ';
    $sort = "ORDER BY uf.link_mark DESC, uf.only_mark ASC";
    if ($time<1435593600) {

        $time_num =1;
        $where = $where . "AND link_mark > 0 AND only_mark >0 ";
    }
    elseif ($time>1435593600&&$time<1436889600) {
        $time_num =2;
        $where = $where . "AND link_mark > 0 AND only_mark >0 AND height_mark > 0 ";
    }
    elseif ($time>1436889600&&$time<1439136000) {
        $time_num =3;
    }
    elseif ($time>1439136000) {
        $time_num =4;
    }


    /*获取已填写的用户信息*/
    $sql =  " SELECT uf.user_id,uf.money, uf.realname ,uf.link_mark,uf.only_mark,uf.height_mark,uf.recruit_school FROM " . $ecs->table('user_freeplan') . " uf"." WHERE $where $sort LIMIT 0,10";
    $mark_list = $db->getAll($sql);
        /*虚假数据*/
    require(ROOT_PATH . './data/false_data.php');
    if (count($mark_list)<100) {
       $last_data = array_merge($mark_list,$false_data);
    }
    if (count($last_data)>100) {
        array_splice($last_data, 100);
    }
    $post_data =array_values($last_data);
    $post_data = bubbleSort2($post_data);
    foreach ($post_data as $key => $value) {
            $post_data[$key]['num'] = $key +1;
        if(strlen($post_data[$key]['realname']) > 9){
            $post_data[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 2,2, 'utf-8');
        }else{
            $post_data[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 1,2, 'utf-8');
        }

        if ($value['user_id'] == $_SESSION['user_id']) {
            $user_num = $key+1;
           $smarty->assign('user_num', $user_num);
        }

    }
    $smarty->assign('time_num', $time_num);
    $smarty->assign('post_data', $post_data);
    $smarty->display('library/mark_sort.lbi');
}


/* 获取奖金排行榜内页 */
elseif( $action == 'win_more' ){

    if(!$_SESSION['user_id']){
        header('location:user.php');
    }
    /*821发放奖金数据*/
    require(dirname(__FILE__) . './../data/false_data_2.php');
    $falseNum = count($name2);
   /*组建虚假数据*/
    for ($i=0; $i < $falseNum ; $i++) {
        $user_false2[$i]['address'] =$address2[$i];
        $user_false2[$i]['realname'] =$name2[$i];
        $user_false2[$i]['idcardnumber'] =$idCard2[$i];
        $user_false2[$i]['academy'] =$school2[$i];
        $user_false2[$i]['money'] =$money2[$i];
    }
    $user_false2 = bubbleSort2($user_false2,"money");
    $user_false2 = array_values($user_false2);

    
    foreach ($user_false2 as $key => $value) {
        $user_false2[$key]['key'] = $key+1;
        //判断姓名字数从而截取不同位数
        if(strlen($user_false2[$key]['realname']) > 9){
            $user_false2[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 2,2, 'utf-8');
        }else{
            $user_false2[$key]['realname'] = '<font style="font-family:宋体"> *</font>'.mb_substr($value['realname'], 1,2, 'utf-8');
        }
        $user_false2[$key]['idcardnumber'] = substr($value['idcardnumber'],0,4).'<font style="font-family:宋体">*********</font>'.substr($value['idcardnumber'],-4);
    }
    $smarty->assign('user_false2',      $user_false2);    // 发放奖金数据

    $sign = isset($_REQUEST['sign']) ? $_REQUEST['sign'] : '';

    $back_url = 'freeplan.php';

    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('back_url', $back_url);
    $smarty->assign('top_title', '获奖风云榜');
    $smarty->assign('user_id', $_SESSION['user_id']);
    $smarty->assign('sign', $sign);
    $smarty->assign('rank_list', $rank_list);
    $smarty->assign('action', $action);
    $smarty->assign('num', $_REQUEST['num']);
    $smarty->display('freeplan/freeplan.dwt');
}







/* 金额数字格式化 */
function num_format($num){
    if(!is_numeric($num)){
        return false;
    }
    $num = explode('.',$num);//把整数和小数分开
    $rl = $num[1];//小数部分的值
    $j = strlen($num[0]) % 3;//整数有多少位
    $sl = substr($num[0], 0, $j);//前面不满三位的数取出来
    $sr = substr($num[0], $j);//后面的满三位的数取出来
    $i = 0;
    while($i <= strlen($sr)){
        $rvalue = $rvalue.','.substr($sr, $i, 3);//三位三位取出再合并，按逗号隔开
        $i = $i + 3;
    }
    $rvalue = $sl.$rvalue;
    $rvalue = substr($rvalue,0,strlen($rvalue)-1);//去掉最后一个逗号
    $rvalue = explode(',',$rvalue);//分解成数组
    if($rvalue[0]==0){
        array_shift($rvalue);//如果第一个元素为0，删除第一个元素
    }
    $rv = $rvalue[0];//前面不满三位的数
    for($i = 1; $i < count($rvalue); $i++){
        $rv = $rv.','.$rvalue[$i];
    }
    $rv?$rv:$rv='0';
    if(!empty($rl)){
        $rvalue = $rv.'.'.$rl;//小数不为空，整数和小数合并
    }else{
        $rvalue = $rv;//小数为空，只有整数
    }
    return $rvalue;
}

/* 以商品ID获取商品信息 */
function goodsid_get_goods($goods_id)
{
    /* 获得商品列表 */
    $sql = 'SELECT g.goods_id, g.shop_price, g.goods_name,g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_thumb, ' .
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " .
        'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
        "WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.goods_id IN ($goods_id) LIMIT 5,3";
    $arr = $GLOBALS['db']->getAll($sql);
    foreach ($arr as $key => $value)
    {
        if ($value['promote_price'] > 0){
            $promote_price = bargain_price($value['promote_price'], $value['promote_start_date'], $value['promote_end_date']);
        }else{
            $promote_price = 0;
        }
        $arr[$key]['goods_id']            = $value['goods_id'];
        $arr[$key]['shop_price']          = $value['shop_price'];
        $arr[$key]['goods_name']          = $value['goods_name'];
        $arr[$key]['promote_price']       = ($promote_price > 0) ? price_format($value['promote_price']) : '';
        $arr[$key]['goods_thumb']         = get_image_path($value['goods_id'], $value['goods_thumb'], true);
        $arr[$key]['url']                 = build_uri('goods', array('gid'=>$value['goods_id']), $value['goods_name']);
        $arr[$key]['counts']              = $value['counts'];
    }
    return $arr;
}
/*冒泡排序算法*/
function bubbleSort2($numbers,$key='link_mark',$sort='desc') {
        foreach ($numbers as $key_1 => $value_1) {

            foreach ($numbers as $key_2 => $value_2) {
                    if (!empty($numbers[$key_2 + 1][$key])) {
                        if ($numbers[$key_2][$key] < $numbers[$key_2 + 1][$key]) {
                            $temp = $numbers[$key_2];
                            $numbers[$key_2] = $numbers[$key_2 + 1];
                            $numbers[$key_2 + 1] = $temp;
                        }
                    }
            }

        }
    return $numbers;
}